/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package kill;

import cn.ac.iie.di.global.GlobalParas;
import java.util.logging.Level;
import org.apache.log4j.Logger;
import sun.misc.Signal;
import sun.misc.SignalHandler;

/**
 *
 *
 */
public class KillHandler implements SignalHandler {

    public static Logger log = Logger.getLogger(KillHandler.class.getName());

    public void registerSignal(String signalName) {
        Signal signal = new Signal(signalName);
        Signal.handle(signal, this);
    }

    @Override
    public void handle(Signal signal) {
        log.info("now receive the system signal " + signal.getName() + " " + signal.getNumber() + "\n\n");
        if (signal.getName().equals("TERM")) {
            log.info("shutting the UnTarFilePath  ... ");
            try {
                GlobalParas.FILE_LISTENER = true;
                log.info("shut FileListener ok ");
                while (true) {
                    if (GlobalParas.FILE_NAME_QUEUE.isEmpty()) {
                        GlobalParas.FILE_READ = true;
                        break;
                    }
                }
                log.info("shut FileRead ok ");
                while (true) {
                    if (GlobalParas.JSON_STR_QUEUE.isEmpty()) {
                        GlobalParas.DWD_FLAG = true;
                        break;
                    }
                }
                log.info("shut DownLoadFile ok ");
                while (true) {
                    if (GlobalParas.JSON_TAR_QUEUE.isEmpty()) {
                        GlobalParas.TAR_FLAG = true;
                        break;
                    }
                }
                log.info("shut TarFilePath ok ");
                log.info("shut AllThread ok ");
                Thread.sleep(1000);
            } catch (Exception ex) {
                log.warn(ex);
            }

        } else {
            log.error("can not process the system signal " + signal.toString());
        }
    }

}
